package com.lagou.code.controller;

import com.lagou.code.remote.EmailService;
import com.lagou.code.remote.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/code")
public class CodeController {
    //key为code:{email}
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserService userService;

    @GetMapping("/create/{email}")
    public boolean generateCode(@PathVariable String email){
        //⽣成验证码并发送到对应邮箱，成功true，失败false
        //先查询有没有这个email的会员
        boolean result  = userService.isRegister(email);
        if(!result){
            Random r = new Random();
            Integer code = r.nextInt(999999);
            redisTemplate.opsForValue().set("code:"+email,code,999, TimeUnit.SECONDS);
            //发送邮件
            emailService.sendMail(email,code.toString());
            return true;
        }
        return false;
    }

    @GetMapping("/validate/{email}/{code}")
    public int validate(@PathVariable String email,@PathVariable String code){
        //校验验证码是否正确
        //0正确1错误2超时
        if(redisTemplate.opsForValue().get("code:"+email) == null){
            return 2;
        }
        String rightCode = redisTemplate.opsForValue().get("code:" + email).toString();
        if(code.equalsIgnoreCase(rightCode)){
            return 0;
        }
        return 1;
    }
}
